<template>
  <div :id="elId" ref="myChart" class="myChart"></div>
</template>

<script>
import { mapGetters } from "vuex";
import common from "@/plugins/common.js";
export default {
  name: "myChart",
  props: {
    option: null,
    isShow: {
      type: Boolean,
      default: true,
    },
    clickEvent: {
      type: Function,
    },
  },
  data() {
    return {
      msg: "hello myChart!",
      elId: "",
      myChart: null,
      sidebarElm: null,
    };
  },
  methods: {
    drawChart() {
      this.$nextTick(() => {
        // 绘制图表
        let element = document.getElementById(this.elId);
        this.myChart = this.$echarts.init(element);
        window.addEventListener("resize", this.__resizeHandler);
        this.sidebarElm = document.getElementsByClassName("asideClass")[0];
        this.sidebarElm &&
          this.sidebarElm.addEventListener(
            "transitionend",
            this.sidebarResizeHandler
          );
        this.myChart.setOption(this.option);
        if (this.clickEvent) {
          if (this.option.title && this.option.title.text) {
            this.myChart.on("click", this.clickEvent);
          } else {
            this.myChart.on("click", this.clickEvent);
          }
        }
      });
    },
    sidebarResizeHandler(e) {
      if (e.propertyName === "width") {
        this.__resizeHandler();
      }
    },
  },
  created() {
    this.elId = parseInt(new Date().getTime() * (Math.random() * 1000));
    this.drawChart();
  },
  mounted() {
    this.__resizeHandler = common.debounce(() => {
      if (this.myChart) {
        this.myChart.resize();
      }
    }, 100);
  },
  watch: {
    option: {
      handler() {
        if (this.myChart) {
          this.myChart.dispose();
        }
        this.drawChart();
      },
      deep: true,
    },
    isShow: {
      handler(newVal) {
        if (newVal) {
          if (this.myChart) {
            this.myChart.resize();
            this.drawChart();
          }
        }
      },
    },
  },
  beforeDestroy() {
    if (this.myChart) {
      this.myChart.dispose();
    }
    window.removeEventListener("resize", this.__resizeHandler);
    this.sidebarElm &&
      this.sidebarElm.removeEventListener(
        "transitionend",
        this.sidebarResizeHandler
      );
  },
};
</script>
<style scoped>
.myChart {
  width: 100%;
  height: 100%;
}
</style>